﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Threading;
using Transitionals;

namespace ViewLED.UI
{
    /// <summary>
    /// Pvideo.xaml 的交互逻辑
    /// </summary>
    public partial class Pvideo : Page
    {
        Screen scr; // 定义一个子窗体，用于在屏幕指定区域播放显示内容
        ArrayList list = new ArrayList();
        private ObservableCollection<Type> transitionTypes = new ObservableCollection<Type>();
        UI.VideoEle v = new VideoEle();
        DispatcherTimer timer = null;
        int s = 0;
        int[] switchTime = new int[7] { 1, 2, 3, 5, 7, 10, 20 };
        bool mutex = true; // 记录下拉显示的变更是鼠标选择还是添删记录造成的标识变量

        public Pvideo()
        {
            InitializeComponent();
            LoadTransitions(Assembly.GetAssembly(typeof(Transition)));
            s--;
            cbxType.SelectedIndex = int.Parse(ConfigurationManager.AppSettings["VideoStretchMode"]);
            getVideoFile();
            list = Model.FileExplorer.listFile("Video", true);
            setAutoChangeVideo();
        }

        private void getVideoFile()
        {
            cbxPreview.ItemsSource = Model.FileExplorer.listFile("Video", false);
        }

        public void setAutoChangeVideo()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        void selTrans()
        {
            int m_nIndex = 0;
            m_nIndex = new Random().Next(0, transitionTypes.Count);
            Type transitionType = transitionTypes[m_nIndex];
            Transition t = (Transition)Activator.CreateInstance(transitionType);
            mainp.Transition = t;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (!v.isPlaying && list.Count > 0)
            {
                v.isPlaying = true;
                selTrans();
                s = (s + 1) % list.Count;
                v.mediaVideo.Source = new Uri(list[s].ToString(), UriKind.Absolute);
                v.StretchType = cbxType.SelectedIndex;
                v.mediaVideo.Play();
                mainp.Content = v;
            }
            removeInvalidItem();
        }

        // 检查下拉列表中是否存在已删除的项目，如果有则清除掉
        // 因为视频文件若正在播放则执行延迟删除处理，无法即时从列表中移除。不过播放列表中是即时处理，显示的下拉文件列表会延迟。
        private void removeInvalidItem()
        {
            ArrayList al = new ArrayList(cbxPreview.Items);
            foreach (string i in al)
            {
                if (!list.Contains(System.AppDomain.CurrentDomain.BaseDirectory + "Video\\" + i))
                {
                    mutex = false;
                    getVideoFile();
                    mutex = true;
                }
            }
        }

        private void cbxType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 对前后两张图设置缩放类型
            v.StretchType = cbxType.SelectedIndex;
            v.StretchType = cbxType.SelectedIndex;
            Model.FileExplorer.setConfig("VideoStretchMode", cbxType.SelectedIndex.ToString());
        }

        // 单独预览某一项
        private void cbxPreview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (mutex)
            {
                list.Clear();
                string p = System.AppDomain.CurrentDomain.BaseDirectory + "Video\\" + cbxPreview.SelectedValue.ToString();
                if (File.Exists(p))
                {
                    list.Add(System.AppDomain.CurrentDomain.BaseDirectory + "Video\\" + cbxPreview.SelectedValue.ToString());
                }
                else
                {
                    mutex = false;
                    getVideoFile();
                    mutex = true;
                }
            }
            v.isPlaying = false;
            v.isPlaying = false;
            timer_Tick(null, null);
        }

        // 删除指定项目
        private void removeItem(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory + "Video\\";
            fd.Filter = "视频文件|*.mp4;*.avi;*.wmv";
            fd.Multiselect = false;
            if (fd.ShowDialog() == DialogResult.OK && fd.FileName.IndexOf(fd.InitialDirectory) == 0)
            {
                mutex = false;
                list.Remove(fd.FileName);
                if (Model.FileExplorer.removeFile("Video\\" + fd.SafeFileName))
                {
                    list.Remove(fd.FileName);
                    getVideoFile();
                }
                mutex = true;
            }
        }

        // 添加新项目
        private void addNewItem(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "视频文件|*.mp4;*.avi;*.wmv";
            fd.Multiselect = false;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                mutex = false;
                if (Model.FileExplorer.addFile(fd.FileName, System.AppDomain.CurrentDomain.BaseDirectory + "Video\\" + fd.SafeFileName))
                {
                    list = Model.FileExplorer.listFile("Video", true);
                    getVideoFile();
                }
                mutex = true;
            }
        }

        // 恢复完整播放
        private void resetPlay(object sender, RoutedEventArgs e)
        {
            mutex = false;
            list = Model.FileExplorer.listFile("Video", true);
            getVideoFile();
            v.isPlaying = false;
            v.isPlaying = false;
            timer_Tick(null, null);
            mutex = true;
        }

        // 大屏幕对外正式播放
        private void playList(object sender, RoutedEventArgs e)
        {
            // 关闭已有的播放屏幕
            Model.ScreenManager.closeScreen();
            // 创建新屏幕
            scr = new Screen();
            scr.Show();
            scr.playVideo();
            // 对外播放时暂停预览界面的播放
            timer.Stop();
        }

        // 退出当前播放
        private void quitPlay(object sender, RoutedEventArgs e)
        {
            Model.ScreenManager.closeScreen();
            // 退出对外播放后恢复预览界面的播放
            timer.Start();
        }

        // 调用特效库
        public void LoadTransitions(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (transitionTypes.Contains(type)) { continue; }

                if ((typeof(Transition).IsAssignableFrom(type)) && (!type.IsAbstract))
                {
                    transitionTypes.Add(type);
                }
            }
        }
    }
}
